package cn.com.cetccst.compliancecheck.checker;

import android.content.Context;

import cn.com.cetccst.compliancecheck.R;
import cn.com.cetccst.compliancecheck.location.GeoFencerExecutor;
import cn.com.cetccst.datacenter.policy.fence.GFence;
import cn.com.cetccst.tools.log.CommonLogger;

public class LocationChecker extends Checker implements GeoFencerExecutor.IFenceListener {

    //STAYED 停留在围栏内
    private static final String[] statusMsg = {
            "UNKNOWN", "IN", "OUT", "STAYED", "LOCFAIL"
    };
    private int innerOrOuter;
    private GFence geoFence;
    private GeoFencerExecutor fencerExecutor;
    private static LocationChecker instance;

    private LocationChecker(Context context) {
        super(CheckerType.Location);
        name = context.getString(R.string.compliance_location);
        if (fencerExecutor == null) {
            fencerExecutor = new GeoFencerExecutor(context, this);
        }
    }

    public static void init(Context context) {
        if(instance == null) {
            instance = new LocationChecker(context);
        }
    }

    public static LocationChecker getInstance() {
        return instance;
    }

    @Override
    public void check(Context context) {
        CommonLogger.info("Start check location:" + fencerExecutor.getFenceStatus());
    }

    @Override
    public void handleFenceStatusChanged(int status) {
        super.check(null);
        if (!isEnable())
            return;

        String str = "";
        if (status < statusMsg.length) {
            str = statusMsg[status];
        }
        if (getInnerOrOuter() == status)
            setResult(CheckResult.Pass);
        else
            setResult(CheckResult.Violated);

        CommonLogger.info("fence status change to:[%d:%s]", status, str);

        //状态发生变化，重新持久化
        CheckerManager.getInstance().saveChecker(this);
    }

    public int getInnerOrOuter() {
        return innerOrOuter;
    }

    public void setInnerOrOuter(int innerOrOuter) {
        this.innerOrOuter = innerOrOuter;
    }

    public GFence getGeoFence() {
        return geoFence;
    }

    public void setGeoFence(GFence geoFence) {
        this.geoFence = geoFence;
        fencerExecutor.addFences(geoFence);
    }

}
